package AdminControl;

import java.io.File;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import Model.Mobile;

/**
 * Servlet implementation class DeleteProduct
 */
public class DeleteProduct extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DeleteProduct() {
        super();
        // TODO Auto-generated constructor stub
    }
    
    public static void deleteProduct(String mobileID, String imageSource, String thumbnailSource) {
        //Xoa anh tren Server
        deleteImage(imageSource, thumbnailSource);

        //Xoa trong CSDL
        Mobile mm= new Mobile();
        mm.deleteMobile(Integer.parseInt(mobileID));
      //  Mobile.deleteMobile(mobileID);
    }

    private static void deleteImage(String imageSource, String thumbnailSource) {
        // A File object to represent the filename
        File f1 = new File(imageSource);
        File f2 = new File(thumbnailSource);

        // Make sure the file or directory exists and isn't write protected
        if (!f1.exists() || !f2.exists()) {
            throw new IllegalArgumentException(
                    "Delete: no such file or directory");
        }

        if (!f1.canWrite() || !f2.canWrite()) {
            throw new IllegalArgumentException("Delete: write protected");
        }

        // Attempt to delete it
        boolean success1 = f1.delete();
        boolean success2 = f2.delete();

        if (!success1 || !success2) {
            throw new IllegalArgumentException("Delete: deletion failed");
        }
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		 response.setContentType("text/html;charset=UTF-8");

	        String mobileID = request.getParameter("mobileID");


	        String imageSource = getServletContext().getRealPath("") + "\\" + Mobile.getMobileImage(mobileID);
	        String thumbnailSource = getServletContext().getRealPath("") + "\\" + Mobile.getMobileThumbnail(mobileID);
	        deleteProduct(mobileID, imageSource, thumbnailSource);

	        response.sendRedirect("ProductManage.jsp");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
